package cn.itcast.zuul.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 获取zuul的上下文对象
        RequestContext context = RequestContext.getCurrentContext();

        // 获取request对象
        HttpServletRequest request = context.getRequest();

        // 获取token参数
        String token = request.getParameter("token");

        // 没有token就拦截，不再分发请求
        if (StringUtils.isBlank(token)) {
            // 不转发请求
            context.setSendZuulResponse(false);
            // 认证未通过，响应401
            context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            // 设置响应信息
            context.setResponseBody("{\"status\": 401, \"text\": \"request error\"}");
        }
        context.set("token", token);
        // 直接放行
        return null;
    }
}
